<?php
/**
 * Created by PhpStorm.
 * User: dx
 * Date: 16/2/19
 * Time: 下午4:20
 */
class Coupons extends Eloquent
{
    protected $table = "coupons";

    public static $type = array(
        "1"=>"订单减免券",
        "2"=>"服务抵用券",
        "3"=>"实物抵用券",
        "4"=>"服务减免券",
        "5"=>"服务折扣券",
    );
    public static $statsu = array(
        '1' => '生成',
        '2' => '领取',
        '3' => '锁定',
        '4' => '使用',
        '5' => '作废',
        '6' => '过期',
    );

    /**
     * @Author:      lyt
     * @DateTime:  2017-08-31 09:36:29
     * @Description: 暂时的 邀请返券活动
     * 传入 用户 查看用户是不是被邀请 有没有送券
     */
    public static  function InvitationCoupon($user_id){
        return DB::transaction(function () use ($user_id) {
            $uii=UserInvitation::where("invite_user_id",$user_id)->first();
            if($uii){//如果有邀请关系 继续没有结束
                $uitc=UserInvitationCoupon::where("user_invitation_id",$uii->id)->where("type",2)->first();
                if(is_null($uitc)){
                    $response=array();
                    $activity = Coupons::getNewUserRegister(Config::get('c_config.invite_register_activity_id'),$response);
                    if(!is_null($activity)){
                        foreach ($activity as  $v) {
                            $coupon_base_info = Coupons::getCouponBaseInfo($v->coupon_base_info_id);
                            if (!$coupon_base_info) {
                                break;
                            }
                            if ($coupon_base_info->status == 0) {
                                break;
                            }
                            if ($coupon_base_info->date_type == 0 && strtotime($coupon_base_info->end_date.' 23:59:59') < strtotime(date('Y-m-d H:i:s', time()))) { //起止时间
                                break;
                            }
                            $coupon_whether_exist = Coupons::getCouponOther($v->coupon_base_info_id);
                            if (!is_null($coupon_whether_exist)) {
                                $coupons = Coupons::find($coupon_whether_exist->id);
                                $coupons->status = 2;
                                $coupons->received_user_id = $uii->user_id;
                                $coupons->get_time = date("Y-m-d H:i:s", time());
                                if ($coupon_base_info->date_type == 1) { //顺延日期
                                    $coupons->end_date = date("Y-m-d", strtotime("+" . $coupon_base_info->date_num . " day"));
                                }
                                $coupons->save();
                                //记录推送优惠券信息
                                $uitc=new UserInvitationCoupon;
                                $uitc->activity_base_id=Config::get('c_config.invite_register_activity_id');
                                $uitc->user_invitation_id=$uii->id;
                                $uitc->type=2;
                                $uitc->save();
                            }
                        }
                    }
                }
            }
        });
    }

    /**
     * @Author:      lyt
     * @DateTime:    2016-03-30 15:05:26
     * @Description: 用于订单取消的时候 回复优惠券的方法
     */
    // public static  function canelOrder($order_id){
    // 	return DB::transaction(function () use ($order_id) {
	   //  	$check_coupon = CouponOrderInfo::where('order_id',$order_id)->where('status',1)->lockForUpdate()->first();
	   //  	if($check_coupon){
	   //  	    $check_coupon->status=0;
		  //       $check_coupon->save();
	   //          Coupons::where("coupon_base_info_id",$check_coupon->coupon_base_info_id)->where("received_user_id",$check_coupon->user_id)->where("code",$check_coupon->code)->update(array("status"=>2,"use_time"=>"0000-00-00 00:00:00","used_user_id"=>0));	            
	   //      }
	   //  });
    // }

    /**
     * @Author:      zwh
     * @DateTime:    2016-11-25 14:38:22
     * @Description: 用于订单抵用券结算时未使用返还 取消 终结订单调用
     */
    public static  function returnCoupon($order_id){
        return DB::transaction(function () use ($order_id) {
            Coupons::payCoupon($order_id);
	    	$check_coupon = CouponOrderInfo::where('order_id',$order_id)->where('status',1)->lockForUpdate()->get();
	    	if($check_coupon){
	    	    foreach($check_coupon as $cc){
	    	        $cc->status=0;
	    	        $cc->save();
	    	        Coupons::where("id",$cc->coupon_id)->where("received_user_id",$cc->user_id)->where("code",$cc->code)->update(array("status"=>2,"use_time"=>"0000-00-00 00:00:00","used_user_id"=>0));
	    	    }
	        }
	        $order=Orders::find($order_id);
	        $order->discount_amount=0;
	        $order->save();
	        Orders::calculate($order_id);
	    });
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-11-25 14:38:22
     * @Description: 用于订单抵用券结算时未使用返还
     */
    /**
     * @Author:      lyt
     * @DateTime:  2017-08-30 13:50:24
     * @Description: 无用法法 测试删除 
     */
    // public static  function returnCoupons($order_id){
    //     return DB::transaction(function () use ($order_id) {
    //         $check_coupon = CouponOrderInfo::leftJoin('coupon_base_info','coupon_base_info.id','=','coupon_order_info.coupon_base_info_id')
    //         ->where('coupon_order_info.order_id',$order_id)
    //         ->where('coupon_order_info.status',1)
    //         ->where('coupon_base_info.type',2)
    //         ->lockForUpdate()
    //         ->first();
    //         if($check_coupon){
    //             $coi=CouponOrderInfo::where('order_id',$order_id)->where('status',1)->first();
    //             $coi->status=0;
    //             $coi->save();
    //             Coupons::where("id",$check_coupon->coupon_id)->update(array("status"=>2,"use_time"=>"0000-00-00 00:00:00","used_user_id"=>0));
    //         }
    //     });
    // }

	//被邀请新用户首单完成奖励邀请人
	public static function invite($order_id){
		try{
			/*判断是否是用户首单*/
			$code = -1;
			$order = Orders::where('order_id',$order_id)->first();
			if(!is_null($order)){
				//是否首单
				$count = Orders::where('user_id',$order->user_id)->whereIn('status',array('1017','1117','1217','1317','1417'))->count();
				if($count == 1){
					//是否有邀请
					$invite_user = UserInvitation::where('invite_user_id',$order->user_id)
						->select(array('user_id'))
						->first();
					if(!is_null($invite_user)){
						$coupon_id =  Coupons::pushCoupons($invite_user->user_id,Config::get('config.invite_coupon_active_id'));
						CompleteOrderFanquan::insert(array(
								'invite_user_id' => $invite_user->user_id,
								'invited_user_id' => $order_id->user_id,
								'coupon_id' => $coupon_id,
							)
						);
						$code = $coupon_id;
					}
				}
			}
		}catch (Exception $e) {
			$code = -2;
		}
		return $code;
	}

	/*送券函数*/
	public static function pushCoupons($user_id,$coupons_activity_id){
		$register_activity = DB::table('activity_base_info')->where('id', $coupons_activity_id)->first();
		if (!is_null($register_activity) && ($register_activity->status != 0)) { //活动存在且没有关闭
			$today = date("Y-m-d");
			if ($today >= $register_activity->begin_date && $today <= $register_activity->end_date) {
				$activity_coupon_info = DB::table('activity_coupon_info')->where('activity_id',$coupons_activity_id)->where('status',1)->get();
				if(!$activity_coupon_info){
					Log::info('pushCoupons',array('activity_id' => $coupons_activity_id));
					return ;
				}
				foreach($activity_coupon_info as $_a_c_i){
					$coupon_base_info = DB::table('coupon_base_info')->where('id',$_a_c_i->coupon_base_info_id)->where('status',1)->first();
					if(!$coupon_base_info){
						Log::info('pushCoupons',array('coupon_base_info_id' => $_a_c_i->coupon_base_info_id));
						return ;
					}

					$coupons = DB::table("coupons")->select('id')
						->where('coupon_base_info_id', $_a_c_i->coupon_base_info_id)
						->where('get_time','0000-00-00 00:00:00')
						->where('use_time','0000-00-00 00:00:00')
						->where('received_user_id', 0)
						->where('used_user_id', 0)
						->where('status',1)
						->first();
					if(!is_null($coupons)){
						if($coupon_base_info->date_type == 1){
							$begin_date = date("Y-m-d",time());
							$end_date = date("Y-m-d",strtotime("+".$coupon_base_info->date_num." day"));
						}else{
							$begin_date = $coupon_base_info->begin_date;
							$end_date = null;
						}
						DB::table("coupons")->where('id', $coupons->id)->update(array("received_user_id" => $user_id, 'get_time' => $begin_date,'end_date' => $end_date ,'status' => 2));
						return $coupons->id;
					}
				}
			}
		}
	}

    // /**
    //  * @Author:      lyt
    //  * @DateTime:    2016-03-30 15:22:00
    //  * @Description: 用于订单结束时候 优惠券置为 使用的方法
    //  */
    // public static function endOrder($order_id){
    // 	return DB::transaction(function () use ($order_id) {
	   //  	$check_coupon = CouponOrderInfo::where('order_id',$order_id)->where('status',1)->first();
	   //  	if($check_coupon){//如果使用了优惠券
	   //          Coupons::where("coupon_base_info_id",$check_coupon->coupon_base_info_id)->where("received_user_id",$check_coupon->user_id)->where("code",$check_coupon->code)->update(array("status"=>4));	            
	   //      }
	   //  });
    // }

    public function users()
    {
        return $this->hasOne('Users',"id","received_user_id");
    }

    public function coupon_order_info()
    {
        return $this->hasOne('CouponOrderInfo',"coupon_base_info_id","coupon_base_info_id");
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-11-25 14:38:22
     * @Description: 用于优惠券可用判断
     */
    public static function isAvailable($coupon_id,$user_id){
        
//         $coupon=Coupons::where('id',$coupon_id)->where('received_user_id',$user_id)->first();
//         if(!$coupon){ //没有优惠券
//             return $response = Lang::get("scs_error.order_pay_type_error_40042");
//         }
//         if(!in_array($coupon->status,array(2,3,4))){ //说明优惠券状态不对
//             return $response = Lang::get("scs_error.order_pay_type_error_40042");
//         }
//         $cbi=CouponBaseInfo::find($coupon_id);
//         if(!$coupon_base_info){ //优惠券基本信息不存在
//             return $response = Lang::get("scs_error.order_pay_type_error_40042");
//         }
//         if(strtotime($coupon->end_date.' 23:59:59') < time()){ //优惠券已过期
//              return $response = Lang::get("scs_error.order_pay_type_error_40042");
//         }
//         return array("code"=>0,"msg"=>"ok");
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-03-10 15:55:27
     * @Description: 验证优惠券吗
     */
    public static function verification_coupons($order,$code){
    	return DB::transaction(function () use ($order,$code) {
            $response = array('code' => 0, 'msg' => 'ok');   
            $orders=Orders::find($order->order_id);         
            $coupon=Coupons::where('received_user_id',$orders->user_id)
                ->leftJoin('coupon_base_info','coupon_base_info.id','=','coupons.coupon_base_info_id')
                ->where('coupons.code',$code)
                ->select('coupons.id',"coupons.used_car_no",'coupons.code','coupons.status','coupons.coupon_base_info_id','coupons.end_date as end_date_1','coupon_base_info.end_date as end_date_2','coupon_base_info.begin_date as start_date','coupon_base_info.date_type')
                ->lockForUpdate()
                ->first();
            if(is_null($coupon)){
                return $response = Lang::get("scs_error.order_coupon_error_40071");
            }
            if(!in_array($coupon->status,array(2))){ //说明优惠券状态不对
                return $response = Lang::get("scs_error.order_coupon_error_40073");
            }
            $cbi=CouponBaseInfo::find($coupon->coupon_base_info_id);
            if(!$cbi){ //优惠券基本信息不存在
                return $response = Lang::get("scs_error.order_coupon_error_40074");
            }
            
            if($cbi->limit_order==1){ //如果是上门
                return $response = Lang::get("scs_error.order_coupon_error_40092");
            }
            if($coupon->date_type==0){
                if(strtotime($coupon->end_date_2.' 23:59:59') < time()||strtotime($coupon->start_date.' 00:00:00')>time()){ //优惠券已过期
                     return $response = Lang::get("scs_error.order_coupon_error_40075");
                }
            }else{
                if(strtotime($coupon->end_date_1.' 23:59:59') < time()){ //优惠券已过期
                    return $response = Lang::get("scs_error.order_coupon_error_40075");
                }
            }
            if($cbi->limit_car==1){
                if($coupon->used_car_no !=$orders->car_no){ //优惠券已过期
                     return $response = Lang::get("scs_error.order_coupon_error_40091");
                }
            }
            if($cbi->limit_book==1&&$orders->book_type==2){
                return $response = Lang::get("scs_error.order_coupon_error_40130");
            }
            //判断限制类型           
            if($cbi->limit_type==1){//如果是金额限制
                if($cbi->limit_amount>$orders->amount){
                    return $response = Lang::get("scs_error.order_coupon_error_40129");
                }                
            }
            if($cbi->limit_type==2){//如果是服务限制
                $limit_id=CouponPackLimit::where("coupon_base_info_id",$cbi->id)->select("pack_id")->get();
                $limit_arr=array();
                foreach ($limit_id as $_li) {
                    $limit_arr[]=$_li->pack_id;
                }
                $top=OrderProduct::where('order_id',$orders->order_id)->where('product_type','base')->where("status",1)->select("product_id")->get();
                $o_pid=array();
                foreach ($top as $_top) {
                    $o_pid[$_top->product_id]=$_top->product_id;
                }
                $t=array_diff($limit_arr,array_values($o_pid));
                if(sizeof($t)>0){//说明限制的服务订单中 又不存在的 
                    return $response = Lang::get("scs_error.order_coupon_error_40127");
                }
            }
            //门店限制
            $cp=CouponShop::where("coupon_base_id",$cbi->id)->where("shop_id",$orders->shop_id)->where("status",1)->first();
            if(!$cp){ //该优惠券 不适合该门店
                return $response = Lang::get("scs_error.order_coupon_error_40128");
            }
            //优惠金额不能大于订单或者优惠的项目
            switch ($cbi->type) {
                case 1://抵用券                        
                    if($cbi->amount>$orders->amount){//如果优惠金额大于订单今个 取消优惠券
                        return $response = Lang::get("scs_error.order_coupon_error_40080");
                    }
                    break;
                case 2://服务抵用卷
                case 4://服务减免券
                    $pack_arr=CouponPack::where("coupon_base_info_id",$cbi->id)->select("pack_id")->first();
                    if(is_null($pack_arr)){
                        return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                    } 
                    $op=OrderProduct::where('order_id',$orders->order_id)->where('product_id',$pack_arr->pack_id)->where('product_type','base')->where("status",1)->where("amount",">=",$cbi->amount)->orderBy('id','asc')->first();
                    //此处判断 大于优惠金额的 满足优惠服务条件的，该订单的产品包 （由于类型2 服务抵用券优惠金额为0 所以对优惠类型2无影响，服务类型4 服务减免的服务价格不能小于 优惠金额 ）
                    if(is_null($op)){
                        return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                    }                                          
                    break;
                case 3://实物抵用券
                    return $response = Lang::get("scs_error.order_coupon_error_40071");
                    break;                    
                case 5://服务折扣券 无金额限制
                    break;
            }  
            

            //取消替他 正在使用的优惠券状态
            $check_coupon = CouponOrderInfo::where('order_id',$orders->order_id)->where('status',1)->where('val_status',1)->first();
            if($check_coupon){
                $check_cp=Coupons::find($check_coupon->coupon_id);
                $check_cbi=CouponBaseInfo::find($check_cp->coupon_base_info_id);
                switch ($check_cbi->type) {
                    case 2://服务抵用卷
                    case 4://服务减免券
                    case 5://服务折扣券
                        $check_op_ids=OrderProduct::where('order_id',$orders->order_id)->where('product_type','base')->where("status",1)->where("coupon_discount",">",0)->select("id")->get()->toArray();      
                        // $check_op->coupon_discount=0;
                        // $check_op->save();        
                        OrderProduct::whereIn("id",$check_op_ids)->update(array("coupon_discount"=>0));      
                        OrderProductBaseItem::whereIn('order_product_package_id',$check_op_ids)->update(array("discount"=>1));  
                        break;
                } 
                $check_cp->status=3;//如果取消则优惠券状态变为锁定
                $check_cp->save();
                CouponOrderInfo::where('order_id',$orders->order_id)->where('status',1)->update(array("status"=>0,"product_id"=>0));
                CouponOrderProductInfo::where('order_id',$orders->order_id)->where("coupon_id",$check_cp->id)->delete();
                $cr=new CouponRecords;
                $cr->order_id=$orders->order_id;
                $cr->status=0;
                $cr->coupon_id=$check_cp->id;
                $cr->operator=$orders->user_id;
                $cr->save();
            }      

            $temp_coupon_amount=0;
            $temp_op_id=array();
            switch ($cbi->type) {
            	case 1://抵用券            		
            		$temp_coupon_amount=$cbi->amount;
            		break;
            	case 2://服务抵用卷
                    $pack_arr=CouponPack::where("coupon_base_info_id",$cbi->id)->select("pack_id")->first();
                    if(is_null($pack_arr)){
                        return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                    } 
            		$op=OrderProduct::where('order_id',$orders->order_id)->where('product_id',$pack_arr->pack_id)->where('product_type','base')->where("status",1)->orderBy('id','asc')->first();
            		if(is_null($op)){
                        DB::rollback();
            			return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
            		}
            		$temp_coupon_amount=$op->amount;
            		//清空折扣信息
	                if($op->discount > 0){
	                    OrderProductBaseItem::where('order_product_package_id',$op->id)->update(array("discount"=>1));	                  
	                }
            		$op->coupon_discount=$op->amount;
	                $op->discount=0;//折扣优惠清空
	                $op->save();
                    $temp_op_id[]=$op->id;
            		break;
            	case 3://实物抵用券
                    DB::rollback();
            		return $response = Lang::get("scs_error.order_coupon_error_40071");
            		break;
                case 4://服务减免券
                    $pack_arr=CouponPack::where("coupon_base_info_id",$cbi->id)->select("pack_id")->first();
                    if(is_null($pack_arr)){
                        return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                    } 
                    $op=OrderProduct::where('order_id',$orders->order_id)->where('product_id',$pack_arr->pack_id)->where('product_type','base')->where("status",1)->where("amount",">=",$cbi->amount)->orderBy('id','asc')->first();
                    if(is_null($op)){
                        DB::rollback();
                        return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                    }
                    $temp_coupon_amount=$cbi->amount;
                    //清空折扣信息
                    if($op->discount > 0){
                        OrderProductBaseItem::where('order_product_package_id',$op->id)->update(array("discount"=>1));                    
                    }
                    $op->coupon_discount=$cbi->amount;
                    $op->discount=0;//折扣优惠清空
                    $op->save();
                    $temp_op_id[]=$op->id;
                    break;
                case 5://服务折扣券
                    $pack_arr=CouponPack::where("coupon_base_info_id",$cbi->id)->select("pack_id")->get()->toArray();                    
                    $ops=OrderProduct::where('order_id',$orders->order_id)->whereIn('product_id',$pack_arr)->where('product_type','base')->where("status",1)->get();
                    if(sizeof($ops)<=0){
                        return $response = Lang::get("scs_error.order_coupon_pack_error_40076");
                    }
                    foreach ($ops as $_op) {
                        $temp_coupon_amount+=round($_op->amount*(1-$cbi->discount));
                        OrderProductBaseItem::where('order_product_package_id',$_op->id)->update(array("discount"=>$cbi->discount));
                        $_op->coupon_discount=round($_op->amount*(1-$cbi->discount));
                        $_op->discount=0;//折扣优惠清空
                        $_op->save();
                        $temp_op_id[]=$_op->id;
                    }                   
                    break;
            }
            //更改正在使用的优惠券则选中状态
            $coupon=Coupons::find($coupon->id);
            $coupon->status=4;//更改选中则优惠券状态为使用
            $coupon->use_time=date('Y-m-d H:i:s',time());
            $coupon->used_user_id=$orders->user_id;
            $coupon->save();                
            $orders->discount_amount=$temp_coupon_amount;
            $orders->save();
            $coi=new CouponOrderInfo;
            $coi->order_id=$orders->order_id;
            $coi->code=$coupon->code;
            $coi->user_id=$orders->user_id;
            $coi->coupon_base_info_id=$coupon->coupon_base_info_id;
            $coi->status=1;
            $coi->coupon_id=$coupon->id;
            $coi->val_status=1;
            // $coi->product_id=$temp_op_id;
            $coi->product_id=0;
            $coi->save();
            foreach ($temp_op_id as $t_o_p) {
                $copi=new CouponOrderProductInfo;
                $copi->order_id=$orders->order_id;
                $copi->coupon_id=$coupon->id;
                $copi->product_id=$t_o_p;
                $copi->save();
            }
            $cr=new CouponRecords;
            $cr->order_id=$orders->order_id;
            $cr->status=1;
            $cr->coupon_id=$coupon->id;
            $cr->operator=$orders->user_id;
            $cr->save();
            Orders::calculate($orders->order_id);

            try{
                if(isset($coupon)){
                    $push_couopn = CouponPush::Coupons($coupon->id,$coupon->coupon_base_info_id);
                    if(!is_null($push_couopn)){
                        $push_couopn->status = 2;
                        $push_couopn->updated_at = Common::currentTimeString();
                        $push_couopn->save();
                    }
                }
            }catch (Exception $e){
                Log::error("error", array("system" => "scs" ,"event" => "verification_coupons", 'input' =>Input::all() ,"exception" => $e));
            }
            return $response;
        });
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-03-11 14:26:22
     * @Description:检查订单优惠券 检测时候能用 逻辑如果是满减查看是否满足满见，如果是抵用看是否又该服务 该方法用在 每个订单删除产品修改产品的判断上
     */
    public static function check_coupons($order_id){
    	DB::transaction(function () use ($order_id) {
            $response = array('code' => 0, 'msg' => 'ok');
            $orders=Orders::find($order_id);
            if(is_null($orders)){
                return $response = Lang::get("scs_error.order_notexiet_40000");
            }
            $coupon_order=CouponOrderInfo::where('order_id',$orders->order_id)->where('status',1)->where('val_status',1)->first();
            if($coupon_order){//如果订单有正在使用的优惠券 清楚优惠券 配置
            	$coupon=Coupons::find($coupon_order->coupon_id);
	            if(is_null($coupon)){
	                return $response = Lang::get("scs_error.order_coupon_error_40071");
	            }
	            if(!in_array($coupon->status,array(3,4))){ //说明优惠券状态不对
	                return $response = Lang::get("scs_error.order_coupon_error_40073");
	            }
	            $cbi=CouponBaseInfo::find($coupon->coupon_base_info_id);
	            if(!$cbi){ //优惠券基本信息不存在
	                return $response = Lang::get("scs_error.order_coupon_error_40074");
	            }  
                $is_cancel=false;//是否要取消订单优惠券
                if($cbi->limit_type==1){//如果是金额限制
                    if($cbi->limit_amount>$orders->amount){
                        $is_cancel=true;
                    }                
                }
                if($cbi->limit_type==2){//如果是服务限制
                    $limit_id=CouponPackLimit::where("coupon_base_info_id",$cbi->id)->select("pack_id")->get();
                    $limit_arr=array();
                    foreach ($limit_id as $_li) {
                        $limit_arr[]=$_li->pack_id;
                    }
                    $top=OrderProduct::where('order_id',$orders->order_id)->where('product_type','base')->where("status",1)->select("product_id")->get();
                    $o_pid=array();
                    foreach ($top as $_top) {
                        $o_pid[$_top->product_id]=$_top->product_id;
                    }
                    $t=array_diff($limit_arr,array_values($o_pid));
                    if(sizeof($t)>0){//说明限制的服务订单中 又不存在的 
                        $is_cancel=true;
                    }
                }
                // 如果条件满足 查看优惠券优惠的项目存在不存在 或者还符不符合条件
                switch ($cbi->type) {
                    case 1://抵用券                        
                        if($cbi->amount>$orders->amount){//如果优惠金额大于订单今个 取消优惠券
                            $is_cancel=true;
                        }
                        break;
                    case 2://服务抵用卷
                    case 4://服务减免券
                        // $pack_arr=CouponPack::where("coupon_base_info_id",$cbi->id)->select("pack_id")->first();
                        $pack_arr=CouponOrderProductInfo::where('order_id',$orders->order_id)->where("coupon_id",$coupon->id)->first();
                        $op=OrderProduct::where('id',$pack_arr->product_id)->where("status",1)->where("amount",">=",$cbi->amount)->first();
                        //此处判断 大于优惠金额的 满足优惠服务条件的，该订单的产品包 （由于类型2 服务抵用券优惠金额为0 所以对优惠类型2无影响，服务类型4 服务减免的服务价格不能小于 优惠金额 ）
                        if(is_null($op)){
                            $is_cancel=true;
                        }                                          
                        break;                                    
                    case 5://服务折扣券 无金额限制
                        $pack_arr=CouponPack::where("coupon_base_info_id",$cbi->id)->select("pack_id")->get()->toArray();                    
                        $ops=OrderProduct::where('order_id',$orders->order_id)->whereIn('product_id',$pack_arr)->where('product_type','base')->where("status",1)->get();
                        if(sizeof($ops)<=0){
                            $is_cancel=true;
                        }
                        break;
                }

                if($is_cancel){//如果不满足限制条件 要取消该优惠券使用 
                    switch ($cbi->type) {
                        case 2://服务抵用卷
                        case 4://服务减免券
                        case 5://服务折扣券
                            $check_op_ids=OrderProduct::where('order_id',$orders->order_id)->where('product_type','base')->where("status",1)->where("coupon_discount",">",0)->select("id")->get()->toArray();      
                            // $check_op->coupon_discount=0;
                            // $check_op->save();        
                            OrderProduct::whereIn("id",$check_op_ids)->update(array("coupon_discount"=>0));      
                            OrderProductBaseItem::whereIn('order_product_package_id',$check_op_ids)->update(array("discount"=>1));
                            break;
                    } 
                    $coupon->status=3;//如果取消则优惠券状态变为锁定
                    $coupon->save();
                    $coupon_order->status=0;
                    $coupon_order->product_id=0;
                    $coupon_order->save();
                    CouponOrderProductInfo::where('order_id',$orders->order_id)->where("coupon_id",$coupon->id)->delete();
                    $cr=new CouponRecords;
                    $cr->order_id=$orders->order_id;
                    $cr->status=0;
                    $cr->coupon_id=$coupon->id;
                    $cr->operator=$orders->user_id;
                    $cr->save();
                    $orders->discount_amount=0;
                    $orders->save();
                    Orders::calculate($orders->order_id);
                }else{//重新计算 优惠券金额
                    $temp_coupon_amount=0;
                    $temp_op_id=array();
                    switch ($cbi->type) {         
                        case 1://抵用券    
                            $temp_coupon_amount=$cbi->amount;
                            break;               
                        case 2://服务抵用卷
                            $pack_arr=CouponOrderProductInfo::where('order_id',$orders->order_id)->where("coupon_id",$coupon->id)->first();
                            $op=OrderProduct::find($pack_arr->product_id);
                            $temp_coupon_amount=$op->amount;
                            //清空折扣信息
                            OrderProductBaseItem::where('order_product_package_id',$op->id)->update(array("discount"=>1));
                            $op->coupon_discount=$op->amount;
                            $op->discount=0;//折扣优惠清空
                            $op->save();
                            $temp_op_id[]=$op->id;
                            break;                        
                        case 4://服务减免券
                            $pack_arr=CouponOrderProductInfo::where('order_id',$orders->order_id)->where("coupon_id",$coupon->id)->first();
                            $op=OrderProduct::find($pack_arr->product_id);
                            $temp_coupon_amount=$cbi->amount;
                            //清空折扣信息
                            OrderProductBaseItem::where('order_product_package_id',$op->id)->update(array("discount"=>1));
                            $op->coupon_discount=$cbi->amount;
                            $op->discount=0;//折扣优惠清空
                            $op->save();
                            $temp_op_id[]=$op->id;
                            break;
                        case 5://服务折扣券
                            //暂时是 优惠券已经优惠的项目的 修改 如果缺少就去掉 
                            $pack_arr=CouponOrderProductInfo::where('order_id',$orders->order_id)->where("coupon_id",$coupon->id)->select("product_id")->get()->toArray();                    
                            $ops=OrderProduct::whereIn('id',$pack_arr)->where("status",1)->get();                            
                            foreach ($ops as $_op) {
                                $temp_coupon_amount+=round($_op->amount*(1-$cbi->discount));
                                OrderProductBaseItem::where('order_product_package_id',$_op->id)->update(array("discount"=>$cbi->discount));
                                $_op->coupon_discount=round($_op->amount*(1-$cbi->discount));
                                $_op->discount=0;//折扣优惠清空
                                $_op->save();
                                $temp_op_id[]=$_op->id;
                            }                   
                            break;
                    }
                    $orders->discount_amount=$temp_coupon_amount;
                    $orders->save();
                    CouponOrderProductInfo::where('order_id',$orders->order_id)->where("coupon_id",$coupon->id)->delete();
                    foreach ($temp_op_id as $t_o_p) {
                        $copi=new CouponOrderProductInfo;
                        $copi->order_id=$orders->order_id;
                        $copi->coupon_id=$coupon->id;
                        $copi->product_id=$t_o_p;
                        $copi->save();
                    }
                    Orders::calculate($orders->order_id);
                }                 
            } 
        });
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-03-13 09:36:55
     * @Description: 用于结算时 清除绑定的优惠券为 未使用
     */
     public static  function payCoupon($order_id){
        return DB::transaction(function () use ($order_id) {
	    	$check_coupon_ids = CouponOrderInfo::where('order_id',$order_id)->where('status',0)->where('val_status',1)->select("coupon_id")->get()->toArray();//查找所有被锁定的优惠券	    	
	    	Coupons::whereIn("id",$check_coupon_ids)->update(array("status"=>2,"use_time"=>"0000-00-00 00:00:00","used_user_id"=>0));
	    	    
	        
	    });
    }

    public static function getCouponsList($user_id,$status){
        return Coupons::where('received_user_id',$user_id)->where('status',$status)->orderBy('get_time','desc')->get();
    }

    public static function CouponsList($user_id){
        return Coupons::where('received_user_id',$user_id)->orderBy('get_time','desc')->get();
    }

    /*
     * dx
     * activity_id—->activity_coupon_info表查出来coupon_base_info_id
     * coupon_base_info_id——>coupons表里面查user_id和status状态。
     * */
    public static function getCouponInfo($user_id,$activity_id,$bill_time,&$response){
        $activity = Coupons::getActivityBaseInfo($activity_id);
        if(!$activity){ //判断活动是否存在
            $response = Lang::get('error.activity_not_exist');
            return null;
        }
        if($activity->status == 0){
            $response = Lang::get('error.activity_status_error_51001');
            return null;
        }
        if(strtotime($activity->end_date) < strtotime(date('Y-m-d H:i:s',time()))){
            $response = Lang::get('error.activity_game_over_error_51002');
            return null;
        }
        if(strtotime($bill_time) > strtotime($activity->end_date)){
            $response = Lang::get('error.insu_not_exit_error_60000');
            return null;
        }
        if(strtotime($bill_time) < strtotime($activity->begin_date)){
            $response = Lang::get('error.insu_not_exit_error_60000');
            return null;
        }
        $activity_coupon_info = Coupons::getActivityCouponInfo($activity_id);
        if(!$activity_coupon_info){
            $response = Lang::get('error.activity_coupon_relation_not_exist');
            return null;
        }
        return $activity_coupon_info;

    }
    public static function getNewUserRegister($activity_id,&$response){
        $activity = Coupons::getActivityBaseInfo($activity_id);
        if(!$activity){ //判断活动是否存在
            $response = Lang::get('error.activity_not_exist');
            return null;
        }
        if($activity->status == 0){
            $response = Lang::get('error.activity_status_error_51001');
            return null;
        }
        if(strtotime($activity->begin_date) > strtotime(date('Y-m-d H:i:s',time()))){
            $response = Lang::get('error.activity_not_start_error_51011');
            return null;
        }
        if(strtotime($activity->end_date) < strtotime(date('Y-m-d H:i:s',time()))){
            $response = Lang::get('error.activity_game_over_error_51002');
            return null;
        }
        $activity_coupon_info = Coupons::getActivityCouponInfo($activity_id);
        if(!$activity_coupon_info){
            $response = Lang::get('error.activity_coupon_relation_not_exist');
            return null;
        }
        return $activity_coupon_info;
    }
    public static function getActivityBaseInfo($activity_id){
        return DB::table('activity_base_info')->where('id',$activity_id)->first();
    }
    public static function getActivityCouponInfo($activity_id){
        return DB::table('activity_coupon_info')->where('activity_id',$activity_id)->where('status',1)->get();
    }
    public static function getCouponBaseInfo($coupon_id){
        return DB::table('coupon_base_info')->where('id',$coupon_id)->first();
    }
    public static function getCoupons($coupon_id,$user_id,$car_no){
        return DB::table('coupons')->where('coupon_base_info_id',$coupon_id)->where('received_user_id',$user_id)->where('used_car_no',$car_no)->first();
    }
    public static function getCouponOther($coupon_id){
        return DB::table('coupons')->where('coupon_base_info_id',$coupon_id)->where('received_user_id',0)->where('get_time','0000-00-00 00:00:00')->first();
    }
    public static function getReceivedCoupon($coupon_id,$user_id){
        return DB::table('coupons')->where('coupon_base_info_id',$coupon_id)->where('received_user_id',$user_id)->first();
    }
    public static function isCoupons($coupon_base_info_id,$user_id){
        return DB::table('coupons')->where('coupon_base_info_id',$coupon_base_info_id)->where('received_user_id',$user_id)->first();
    }

    public static function getReceivedCouponShare($coupon_id,$user_id){
        return DB::table('coupons')->where('coupon_base_info_id',$coupon_id)->where('received_user_id',$user_id)->count();
    }
}